<?php
defined('IN_IA') or exit('Access Denied');

require_once 'defines.php';
require_once MODULE_FUNC.'functions.php';

class Asterye_waimaixia_plugin_gzhModuleReceiver extends WeModuleReceiver {
	public function receive() {
		$type = $this->message['type'];
		$event = $this->message['event'];

		$this->responseClear();
		// 取消关注
		if ($type == 'unsubscribe') {
            $this->reduceCredit($this);
		}

	}

    // 取消关注减积分及余额
    private function reduceCredit($obj){
        global $_W;
        $settings = $this->module['config'];
        if( empty( $obj->message['from'] ) ){
            $cur_member = pdo_fetch("select id,uniacid,uid,parentid,nickname from ".tablename(MODULE_PREFIX."member")." where openid=:openid order by id desc limit 1",array(':openid'=> strval($obj->message['from']) ));

            $_W['uniacid'] = $cur_member['uniacid'];
            
            if( !empty($cur_member) && !empty($cur_member['parentid']) ){

                $parent_member  = pdo_fetch("select id,uid,openid from ".tablename(MODULE_PREFIX."member")." where id=:id ",array(':id'=>$cur_member['parentid']));
                $sub_log        = pdo_fetchall("select id,reccredit,recmoney,posterid,subcredit,submoney from ".tablename(MODULE_PREFIX."log")." where uid=:uid and from_uid=:from_uid and isunsub = 0 ",array(':uid'=>$cur_member['uid'],':from_uid'=>$parent_member['uid']));
                
                if( empty($sub_log) ){
                    return false;
                }
                
                foreach ($sub_log as $key => $log) {

                    $poster         = pdo_fetch("select templateid,isunsubscribe,unsub_sendval from ".tablename(MODULE_PREFIX."poster")." where id=:id ",array( ':id'=>$log['posterid'] ));

                    # 是否开启取消减积分余额
                    if( !empty($poster['isunsubscribe']) ){

                        # 关注者减少送的积分
                        if($log['subcredit'] > 0){
                            setCredit($cur_member['uid'],'credit1', intval("-".$log['subcredit']) , array(0,"取消关注减".$log['subcredit']."积分！"));
                        }
                        
                        # 关注者减少送的余额
                        if($log['submoney'] > 0){
                            setCredit($cur_member['uid'],'credit2', intval("-".$log['submoney']) , array(0,"取消关注减".$log['submoney']."余额！"));
                        }

                        # 推荐人减积分
                        if($log['reccredit'] > 0){
                            setCredit($parent_member['uid'],'credit1', intval("-".$log['reccredit']) , array(0,"下级用户“".$cur_member['nickname']."”取消关注减".$log['reccredit']."积分！"));
                        }
                        
                        # 推荐人减余额
                        if($log['recmoney'] > 0){
							if($settings['system_type'] == 1){
								$fans = pdo_get("mc_mapping_fans", array("uid" => $parent_member['uid']));
								if($fans['unionid']){
									pdo_update(MODULE_XCXNAME."_user_u", array('money -=' => $log['recmoney']), array("unionid" => $fans['unionid'], "system_id" => $settings['system_id']));
									$user = pdo_get(MODULE_XCXNAME."_user_u", array("unionid" => $fans['unionid'], "system_id" => $settings['system_id']));
								   $result = pdo_insert(MODULE_XCXNAME."_user_logs_u", array("user_id" => $user['user_id'], "system_id" => $settings['system_id'], "num" => $log['recmoney'], "create_time" => $_W["timestamp"], "reason" => '取消关注扣除邀请奖励'));
								}
								//小程序奖励
							}else{
								setCredit($parent_member['uid'],'credit2', intval("-".$log['recmoney']) , array(0,"下级用户“".$cur_member['nickname']."”取消关注减".$log['recmoney']."余额！"));
							}
                            
                        }

                        $res_text = $poster['unsub_sendval'];

                        # 确认取消
                        pdo_update(MODULE_PREFIX."log",array('isunsub'=>1),array('id'=>$log['id']));

                        # 消息推送
                        if(!empty($res_text)){
                            $res_text = str_replace("[nickname]", $cur_member['nickname'], $res_text);
                            $res_text = str_replace("[cur_time]", date('Y-m-d H:i:s',time()), $res_text);
                            $res_text = str_replace("[credit1]", intval($log['reccredit']), $res_text);
                            $res_text = str_replace("[credit2]", sprintf('%.2f', $log['recmoney']), $res_text);
                            
                            if(!empty($poster['templateid'])){
                                sendTplNotice($parent_member['openid'], $poster['templateid'], postdata('','',$res_text));
                            }else{
                                sendCustomNotice($parent_member['openid'], $res_text);
                            }
                        }


                    }

                }


            }
        }

    }

	private function responseClear(){
        echo '';
        ob_clean();
        ob_start();
        echo '';
        ob_flush();
        ob_end_flush();
    }

}